import { useState } from "react";
import { Button } from "antd";
import { PlusOutlined, MinusOutlined } from "@ant-design/icons";
import InputNumberComponent from "@/components/iteration/InputNumberComponent";
import PropTypes from "prop-types";
const CounterNumberComponent = ({ value, minValue, maxValue, onChange, size = "middle" }) => {
  const [count, setCount] = useState(value || 0);

  const handleCallback = (value) => {
    if (value === null || value === undefined || value === "") return;
    onChange && onChange(+value);
  };

  const handleChange = (value, type) => {
    if (type === "AUG") {
      if (maxValue && value > maxValue) return;
      handleCallback(value);
      setCount(+value);
    } else if (type === "DEC") {
      if (minValue === 0 && value < 0) return; // 这里需要处理一下，当最小值为0时，不允许再减
      if (minValue && value < minValue) return;
      handleCallback(value);
      setCount(+value);
    } else {
      if (value === null || value === undefined || value === "") {
        handleCallback(null);
        setCount(null);
      } else {
        handleCallback(value);
        setCount(+value);
      }
    }
  };

  const isDisabled = (value) => {
    if (minValue === 0 && value <= 0) return true;
    if (minValue && value < minValue) return true;
    return false;
  };

  return (
    <div style={{ display: "flex", alignItems: "center" }}>
      <Button
        icon={<MinusOutlined />}
        disabled={isDisabled(count)}
        size={size}
        style={{ borderStartEndRadius: "0px", borderEndEndRadius: "0px", padding: "0px 8px" }}
        onClick={() => handleChange(+count - 1, "DEC")}
      />
      <InputNumberComponent
        value={count}
        min={minValue}
        max={maxValue}
        size={size}
        style={{ borderRadius: "0px" }}
        onChange={(v) => handleChange(v.target.value)}
      />
      <Button
        icon={<PlusOutlined />}
        disabled={count >= maxValue}
        size={size}
        style={{ borderStartStartRadius: "0px", borderEndStartRadius: "0px", padding: "0px 8px" }}
        onClick={() => handleChange(+count + 1, "AUG")}
      />
    </div>
  );
};
CounterNumberComponent.propTypes = {
  value: PropTypes.number,
  minValue: PropTypes.number,
  maxValue: PropTypes.number,
  onChange: PropTypes.func,
  size: PropTypes.oneOf(["small", "middle", "large"]),
};

export default CounterNumberComponent;
